package com.zzm.easyokhttp3.http;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.MediaType;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Locale;

/**
 * @ClassName OkHttpTest
 * @Description Response返回实体
 * @Author zzm
 * @Date 2019/6/12 14:05
 * @Version 1.0
 */
public final class Response {
	/**
	 * HTTP状态码
	 */
	private final int responseCode;
	/**
	 * 错误信息
	 */
	private final String error;
	/**
	 * 地址
	 */
	private final String address;

	private byte[] body;
	/**
	 * 错误异常
	 */
	private Exception exception;

	private Response(int responseCode, String address, String error, byte[] body, Exception e) {
		this.responseCode = responseCode;
		this.error = error;
		this.address = address;
		this.body = body;
		this.exception = e;
	}

	protected static Response create(okhttp3.Response response, String address) throws IOException {
		String error = null;
		int code = response.code();
		byte[] body = response.body().bytes();
		if (!response.isSuccessful() && body != null) {
			error = new String(body);
		}
		return new Response(code, address, error, body, null);
	}

	protected static Response createError(String address, String error, Exception e) {
		return new Response(-1, address, error, null, e);
	}

	private static String ctype(okhttp3.Response response) {
		MediaType mediaType = response.body().contentType();
		if (mediaType == null) {
			return "";
		}
		return mediaType.type() + "/" + mediaType.subtype();
	}

	public boolean isResponseOK() {
		return this.responseCode >= 200 && this.responseCode < 300 && error == null && exception == null;
	}

	public boolean isNetworkBroken() {
		return responseCode == -1;
	}

	public boolean needRetry() {
		return isNetworkBroken() || !isResponseOK();
	}

	@Override
	public String toString() {
		return String.format(Locale.ENGLISH,
				"{responseCode:%d, adress:%s, error:%s}", responseCode, address, error);
	}

	public String getBodyString() {
		if (body == null) {
			return null;
		}
		return new String(body, Charset.forName("UTF-8"));
	}

	public JSONObject getBodyToJson() {
		if (body == null) {
			return null;
		}
		return JSON.parseObject(new String(body, Charset.forName("UTF-8")));
	}

	public <T> T getBodyToClass(Class<T> clazz) {
		if (body == null) {
			return null;
		}
		return JSON.parseObject(new String(body, Charset.forName("UTF-8")), clazz);
	}

	private static boolean isJson(okhttp3.Response response) {
		return ctype(response).equals(Client.JsonMime);
	}

	public int getResponseCode() {
		return responseCode;
	}

	public String getError() {
		return error;
	}

	public String getAddress() {
		return address;
	}

	public byte[] getBody() {
		return body;
	}

	public Exception getException() {
		return exception;
	}
}
